<?php
/**
 * Created by PhpStorm.
 * Script Name: Mpmenu.php
 * Create: 2023/1/2 11:06
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;

use app\common\service\Tenant as TenantService;
use ky\Tree;
use plugin\wechat\app\TenantController;
use plugin\wechat\app\model\MpMenu as MenuM;
use plugin\wechat\app\service\Mp as MpService;
use Support\Request;

class Mpmenu extends TenantController
{
    /**
     * @var MenuM
     */
    protected $model;

    public function __construct()
    {
        parent::__construct(); // TODO: Change the autogenerated stub
        $this->model = new MenuM();
    }

    /**
     * 保存菜单
     * @param Request $request
     * @param string $jump
     * @param array $data
     * @return \support\Response
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\db\exception\DbException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function savePost(Request $request, $jump = '', $data = []){
        if(request()->isPost()){
            $mp_info = $request->mpInfo;
            $post_data = input('post.');
            $menu_list = $post_data['menu_list'];
            $mp_menu = [];  //提交微信的菜单数组
            $ids = []; //保留旧数据
            foreach ($menu_list as $k => $menu){
                if(empty($menu['name'])){
                    return $this->error('所有菜单的名称必填');
                }
                if(empty($menu['_child'])){
                    if(empty($menu['type']) || (empty($menu['key']) && empty($menu['url']) && empty($menu['appid']) && empty($menu['pagepath']))){
                        return $this->error('【'.$menu['name'] . '】菜单的信息填写不完整');
                    }
                }else{
                    foreach ($menu['_child'] as $j => $child){
                        if(empty($child['name'])){
                            return $this->error('所有菜单的名称必填');
                        }
                        if(empty($child['type']) || (empty($child['key']) && empty($child['url']) && empty($child['appid']) && empty($child['pagepath']))){
                            return $this->error('【'.$child['name'] . '】菜单的信息填写不完整');
                        }
                    }
                }

                $data = [
                    'name' => $menu['name'],
                    'sort' => $k,
                    'type' => $menu['type'],
                    'key'  => $menu['key'],
                    'url'  => $menu['url'],
                    'appid' => $menu['appid'],
                    'pagepath' => $menu['pagepath']
                ];
                $mp_menu_top = [ //提交微信的一级菜单
                    'name' => $menu['name'],
                ];
                if(!empty($menu['id'])){
                    $data['id'] = $menu['id'];
                    $this->model->update($data);
                    $top_menu = $data;
                }else{
                    $data['mp_id'] = $mp_info['id'];
                    $data['company_id'] = TenantService::getCompanyId();
                    $data['pid'] = 0;
                    $top_menu = $this->model->createOne($data);
                }
                $ids[] = $top_menu['id'];
                if(!empty($menu['_child'])){
                    $mp_menu_top['sub_button'] = [];
                    foreach ($menu['_child'] as $j => $child){
                        array_push($mp_menu_top['sub_button'], [
                            'name' => $child['name'],
                            'type' => $child['type'],
                            'key'  => $child['key'],
                            'url'  => $child['url'],
                            'appid' => $child['appid'],
                            'pagepath' => $child['pagepath']
                        ]);

                        $child_data = [
                            'pid' => $top_menu['id'],
                            'name' => $child['name'],
                            'sort' => $j,
                            'type' => $child['type'],
                            'key'  => $child['key'],
                            'url'  => $child['url'],
                            'appid' => $child['appid'],
                            'pagepath' => $child['pagepath']
                        ];
                        if(!empty($child['id'])){
                            $child_data['id'] = $child['id'];
                            $this->model->update($child_data);
                        }else{
                            $child_data['mp_id'] = $mp_info['id'];
                            $child_data['company_id'] = TenantService::getCompanyId();
                            $child = $this->model->createOne($child_data);
                        }
                        $ids[] = $child['id'];
                    }
                }else{
                    $mp_menu_top = array_merge($mp_menu_top, [
                        'type' => $menu['type'],
                        'key'  => $menu['key'],
                        'url'  => $menu['url'],
                        'appid' => $menu['appid'],
                        'pagepath' => $menu['pagepath']
                    ]);
                }
                array_push($mp_menu, $mp_menu_top);
            }

            if(count($mp_menu)){
                //删除废弃的菜单
                if($ids){
                    $this->model->where('id' , 'notin', $ids)
                        ->where('mp_id' , '=', $mp_info['id'])
                    ->delete();
                }

                $res = MpService::createMenus($mp_info, $mp_menu);
                if($res === true){
                    return $this->success('发布成功');
                }
                return $this->error('发布失败,失败原因:' . $res);
            }else{
                return $this->error('请提交菜单数据');
            }
        }
    }

    /**
     * 自定义菜单设置
     * @param Request $request
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function index(Request $request){
        $mp_info = $request->mpInfo;
        if($mp_info['verify_type_info'] < 0 && $mp_info['service_type_info'] != 2){
            return $this->error('当前公众号未获得自定义菜单编辑权限');
        }

        $query = $this->model->where([
            $this->tenantWhere(),
            ['mp_id', '=', $mp_info['id']]
        ]);
        $total = $query->count();
        if($total < 1){
            MpService::pullMenus($mp_info);
        }
        $menu_list = $query->field(['id','pid','name','type','sort','key','url','appid','pagepath'])
            ->order(['sort' => 'asc'])
            ->select();
        if(count($menu_list)){
            foreach ($menu_list as &$value){
                $value['selected'] = 0;
                $value['_child'] = [];
            }
            $menu_list = Tree::listToTree($menu_list, 'id', 'pid', '_child');
        }
        $assign = ['menu_list' => json_encode($menu_list, JSON_UNESCAPED_UNICODE), 'types' => MpService::menuTypes()];
        return $this->show($assign);
    }
}